<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocketTest</title>
    <script type="text/javascript" src="http://www.w3school.com.cn/jquery/jquery-1.11.1.min.js"></script>
</head>
<body>
<script>
    var socket;
    if(window.WebSocket){
        socket = new WebSocket("ws://localhost:8080/");
        // websocket收到消息
        socket.onmessage = function(event){
            // 如果服务端是写的二进制数据，则此处的blob也是一个二进制对象，提取数据时需要Blob类和FileReader类配合使用
            var blob = event.data;
            var content = $("#content").html();
            blob += content;
            $("#content").html(blob);
        };

        // websocket连接打开
        socket.onopen = function (event) {
            console.log("websocket 连接打开");
        };

        // websocket连接关闭
        socket.onclose = function (event) {
            console.log("websocket 连接关闭");
        };
    }else{
        alert("你的浏览器不支持websocket");
    }

    function send(message) {
        if(!window.WebSocket){
            return;
        }
        if(socket.readyState == WebSocket.OPEN){
            socket.send(message);
        }else{
            alert("websocket连接未打开，请检查网络设置");
        }
    }
</script>
<form onsubmit="return false;">
    <input type="text" name="message">
    <input type="button" value="提交" onclick="send(this.form.message.value)">
    <div id="content"></div>
</form>
</body>
</html>
